<?php

namespace Miniapp\Controllers;

use Phalcon\Mvc\Controller;

class WechatController extends BaseController {

    protected $openid;
    protected $token;
    protected $wxNickname;
    protected $wxImg;
    protected $city;
    protected $sex; //用户的性别，值为1时是男性，值为2时是女性，值为0时是未知
    protected $appid = WX_QMZF_SERVICER_NUMBER_APPID;
    protected $secret = WX_QMZF_SERVICER_NUMBER_APPSECRET;
    protected $callback = "https%3A%2F%2Fapp.gjgj.com%2FWxauth%2FWechatWebAuthentication"; //urlencode("http://app.gjgj.com/Wxauth/WechatWebAuthentication");GJGJ服务号通用鉴权页面
    protected $redirectUrl;

    public function getQmzfOpenIdAction() {
        //获取当前请求页面
        $url = 'https://' . $_SERVER['SERVER_NAME'] . ':' . $_SERVER["SERVER_PORT"] . $_SERVER["REQUEST_URI"];
        //设置真实跳转页面
        $trueCallback = base64_encode($url);
        $this->callback = $this->callback . (urldecode("?trueCallback=") . $trueCallback);
        //定义获取TOKEN出错时重新跳转到首页URL的请求
        $callbackIndexUrl = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" . $this->appid . "&redirect_uri=" . $this->callback . "&response_type=code&scope=snsapi_base&state=0#wechat_redirect";
        $this->redirectUrl = $callbackIndexUrl;
        if (empty($_GET['code'])) {
            //获取当前页面跳转URL
            header('Location: ' . $this->redirectUrl);
            exit();
        }
        $redisKey = getRedisKey("SYSTEM", "CODE_OPEN_ID", $_GET['code']);
        if ($this->redisCache->exists($redisKey)) {
            $tokenArray['openid'] = $this->redisCache->get($redisKey);
        } else {
            $tokenUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=" . $this->appid . "&secret=" . $this->secret . "&code=" . $_GET['code'] . "&grant_type=authorization_code";
            $tokenStc = file_get_contents($tokenUrl);
            $tokenArray = json_decode($tokenStc, true);
            $this->redisCache->set($redisKey, $tokenArray['openid']);
            $this->redisCache->expire($redisKey, 600);
        }
        $this->view->openId = urlencode($tokenArray['openid']);
        $this->view->pick("Wechat/index");
    }

}
